#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mutex1;// 创建锁变量1
pthread_mutex_t mutex2;// 创建锁变量2

int ticket = 100;

void* thread_run1(void* arg)
{
  char* name = (char*)arg;
  pthread_mutex_lock(&mutex1);
  int count = 0;
  while (1){
    if (count++ == 5){
      printf("%s is requesting a lock...\n", name);
      //pthread_mutex_unlock(&mutex1);
      pthread_mutex_lock(&mutex2);
    }
    printf("%s is running...\n", name);
    sleep(1);
  }
  pthread_mutex_unlock(&mutex1);
}

void* thread_run2(void* arg)
{
  char* name = (char*)arg;
  pthread_mutex_lock(&mutex2);
  int count = 0;
  while (1){
    if (count++ == 5){
      printf("%s is requesting a lock...\n", name);
      //pthread_mutex_unlock(&mutex2);
      pthread_mutex_lock(&mutex1);
    }
    printf("%s is running...\n", name);
    sleep(1);
  }
  pthread_mutex_unlock(&mutex2);
}

int main()
{
  pthread_t t1, t2;
  // 初始化锁
  pthread_mutex_init(&mutex1, NULL);
  pthread_mutex_init(&mutex2, NULL);
  // 创建2个线程
  pthread_create(&t1, NULL, thread_run1, (void*)"thread 1");
  pthread_create(&t2, NULL, thread_run2, (void*)"thread 2");
  
  
  // 释放5个线程
  pthread_join(t1, NULL);
  pthread_join(t2, NULL);
  // 销毁锁
  pthread_mutex_destroy(&mutex1);
  pthread_mutex_destroy(&mutex2);
  return 0;
}
